package com.xbai.acl.service.service.impl;

import com.xbai.acl.service.entity.User;
import com.xbai.acl.service.service.PermissionService;
import com.xbai.acl.service.service.UserService;
import com.xbai.security.entity.SecurityUser;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xbai
 * @Date 2021/4/27
 */
@Service("userDetailsService")
@RequiredArgsConstructor
public class UserDetailServiceImpl implements UserDetailsService {

    private final UserService userService;

    private final PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询数据
        User user = userService.selectByUsername(username);
        if (user == null) {
            throw  new UsernameNotFoundException("用户不存在");
        }
        com.xbai.security.entity.User currentUserInfo = new com.xbai.security.entity.User();
        BeanUtils.copyProperties(user, currentUserInfo);

        // 根据用户查询用户权限列表
        List<String> permissionValueList = permissionService.selectPermissionValueByUserId(user.getId());
        SecurityUser securityUser = new SecurityUser();
        securityUser.setPermissionValueList(permissionValueList);
        securityUser.setCurrentUserInfo(currentUserInfo);
        return securityUser;
    }
}
